﻿using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using webapp4U.BOL;
using System.Text.RegularExpressions;

namespace webapp4U.UI
{
    public partial class Usercontrol_ShoppingCartDetail : System.Web.UI.UserControl
    {
        private string SCRIPT_DOFOCUS = Forcus.SCRIPT_DOFOCUS;

        public static string InClassKey = "";
        public string ItemKey = "";
        public string error = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Forcus.HookOnFocus(this.Page as Control);                
               
                List<ShoppingCart> ListShopCart = new List<ShoppingCart>();
                if (Session["ShoppingCart"] != null)
                {
                    ListShopCart = (List<ShoppingCart>)Session["ShoppingCart"];
                    GridViewItem.DataSource = ListShopCart;
                    GridViewItem.DataBind();
                    //kiểm tra và đưa startkit vào
                    if (Session["UserName"] != null)
                    { 
                        //kiểm tra xem có phải đơn hàng đầu tiên
                        if (ShoppingCart.CheckFirstOrderBySalespKey(ref error, Session["UserName"].ToString()))
                        {
                            List<ShoppingCart> ListItemStartKit = new List<ShoppingCart>();
                            ListItemStartKit = ShoppingCart.GetItemStartKit(ref error);
                            Session["ItemStartKit"] = ListItemStartKit;
                            GridViewItemStarkit.DataSource = ListItemStartKit;
                            GridViewItemStarkit.DataBind();
                            GridViewItemStarkit.Visible = true;
                        }
                        else
                        {
                            Session["ItemStartKit"] = null;
                            GridViewItemStarkit.Visible = false;
                        }
 
                    }
                }
                
            }


            ScriptManager.RegisterStartupScript(this, typeof(Usercontrol_ShoppingCartDetail), "ScriptDoFocus", SCRIPT_DOFOCUS.Replace("REQUEST_LASTFOCUS", Request["__LASTFOCUS"]), true);
            if (GridViewItem.Rows.Count <= 0)
                PanelUpdate.Visible = false;

        }

        protected string GetInClassKeyByItemKey()
        {
            //Products obj = Products.GetProductsByItemKey(ItemKey, ref error);
            return InClassKey; //obj.InClassKey;
        }

        protected Double GetTotalShoppingCart()
        {

            double total = 0;
            List<ShoppingCart> ListShopCart = new List<ShoppingCart>();
            if (Session["ShoppingCart"] != null)
            {
                ListShopCart = (List<ShoppingCart>)Session["ShoppingCart"];
                total = ShoppingCart.GetTotalShoppingCart(ListShopCart);
                if (Session["ItemStartKit"] != null)
                {
                    total = total + ShoppingCart.GetTotalShoppingCart((List<ShoppingCart>)Session["ItemStartKit"]);
                }
            }

            return total;
        }


        protected void btDelete_Click(object sender, EventArgs e)
        {
            List<ShoppingCart> ListShopCart = new List<ShoppingCart>();
            if (Session["ShoppingCart"] != null)
            {
                ListShopCart = (List<ShoppingCart>)Session["ShoppingCart"];
            }

            else
            {
                Response.Redirect(Globals.ApplicationPath + "Default.aspx?Homepage=");
            }
            for (int i = 0; i < GridViewItem.Rows.Count; i++)
            {
                GridViewRow row = GridViewItem.Rows[i];
                CheckBox chek = ((CheckBox)row.FindControl("chkSelect"));
                bool isChecked = chek.Checked;

                if (isChecked)
                {
                    string ID = chek.ToolTip;
                    foreach (ShoppingCart Item in ListShopCart)
                    {
                        if (Item.ItemKey == ID)
                        {
                            ListShopCart.RemoveAt(ListShopCart.IndexOf(Item));
                            break;
                        }
                    }
                }
            }
            Session["ShoppingCart"] = ListShopCart;
            GridViewItem.DataSource = ListShopCart;
            GridViewItem.DataBind();
            UpdatePanel updatepan = new UpdatePanel();
            updatepan = (UpdatePanel)Page.Master.FindControl("UpdatePanel1");
            updatepan.Update();

        }


        protected void btn_ContinueShopping_Click(object sender, EventArgs e)
        {
            string backUrl = Globals.ApplicationPath + "Default.aspx?Homepage=";
            if (Session["BackPageUrl"] != null)
            {
                backUrl = Session["BackPageUrl"].ToString();
            }
            Response.Redirect(backUrl);            
        }

        protected void txtQuantity_TextChanged(object sender, EventArgs e)
        {
            List<ShoppingCart> ListShopCart = new List<ShoppingCart>();
            if (Session["ShoppingCart"] != null)
            {
                ListShopCart = (List<ShoppingCart>)Session["ShoppingCart"];
            }

            else
            {
                Response.Redirect(Globals.ApplicationPath + "Default.aspx?Homepage=");
            }

            for (int i = 0; i < GridViewItem.Rows.Count; i++)
            {
                GridViewRow row = GridViewItem.Rows[i];

                TextBox txtSoLuong = (TextBox)row.FindControl("txtQuantity");
                //int Quantity = Convert.ToInt32(().Text);
                string ID = ((CheckBox)row.FindControl("chkSelect")).ToolTip;

                //lblToltal.Text = lblToltal.Text + "; So luong:" + txtSoLuong.Text + "; Ma hang:" + txtSoLuong.ToolTip;


                Match MyRegMatch = Regex.Match(txtSoLuong.Text, @"^\d+$");
                if (!MyRegMatch.Success)
                {
                    uscMsgBox1.AddMessage("Bạn hãy nhập số vào đây.", uscMsgBox.enmMessageType.Error);

                    txtSoLuong.Focus();
                    return;
                }
                else if (Convert.ToInt32(txtSoLuong.Text) < 1)
                {
                    uscMsgBox1.AddMessage("Số lượng phải lớn hơn 0.", uscMsgBox.enmMessageType.Error);

                    txtSoLuong.Focus();
                    return;
                }
                foreach (ShoppingCart Item in ListShopCart)
                {
                    if (Item.ItemKey == ID)
                    {
                        Item.Quantity = Convert.ToInt32(txtSoLuong.Text);
                        Item.Subtotal = Item.Quantity * Item.UnitPrice;
                        break;
                    }
                }


            }
            Session["ShoppingCart"] = ListShopCart;
            GridViewItem.DataSource = ListShopCart;
            GridViewItem.DataBind();
            //lblToltal.Text = String.Format("{0:###,###}", ShoppingCart.GetTotalShoppingCart(ListShopCart).ToString());
            ///////////
            // btnRender.

            UpdatePanel updatepan = new UpdatePanel();
            updatepan = (UpdatePanel)Page.Master.FindControl("UpdatePanel1").FindControl("ShoppingCart1").FindControl("UpdatePanelShoppingCart").FindControl("UpdatePanelpnSoppingCart");
            updatepan.Update();
            //StringBuilder sb = new StringBuilder();
            //StringWriter tw = new StringWriter(sb);
            //HtmlTextWriter hw = new HtmlTextWriter(tw);
            ////Usercontrol_ShoppingCart obj = ((MasterPage_Common)this.Page.Master).DataFromPageShoppingCartControl; 

            //((MasterPage_Common)this.Page.Master).DataFromPageShoppingCartControl().RenderControl(hw);

        }


        public string RenderControl(Control ctrl)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter tw = new StringWriter(sb);
            HtmlTextWriter hw = new HtmlTextWriter(tw);

            ctrl.RenderControl(hw);
            return sb.ToString();
        }


        protected void GridViewItem_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            List<ShoppingCart> ListShopCart = new List<ShoppingCart>();
            if (Session["ShoppingCart"] != null)
            {
                ListShopCart = (List<ShoppingCart>)Session["ShoppingCart"];
                ListShopCart.RemoveAt(e.RowIndex);
                if (ListShopCart.Count > 0)
                {
                    Session["ShoppingCart"] = ListShopCart;
                }
                else
                {
                    Session["ShoppingCart"] = null;
                }
            }
            GridViewItem.DataSource = ListShopCart;
            GridViewItem.DataBind();
            //UpdatePanel updatepan = new UpdatePanel();
            //updatepan = (UpdatePanel)Page.Master.FindControl("UpdatePanel1");
            //updatepan.Update();

            UpdatePanel updatepan = new UpdatePanel();
            updatepan = (UpdatePanel)Page.Master.FindControl("UpdatePanel1").FindControl("ShoppingCart1").FindControl("UpdatePanelShoppingCart").FindControl("UpdatePanelpnSoppingCart");
            updatepan.Update();
            
        }
        protected void btnApKM_Click(object sender, EventArgs e)
        {

        }

        private void ApKhuyenMai()
        { 
        
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (Session["ShoppingCart"] != null)
            {
                List<ShoppingCart> ListShopCart = new List<ShoppingCart>();
                ListShopCart = (List<ShoppingCart>)Session["ShoppingCart"];
                GridViewItem.DataSource = ListShopCart;
                GridViewItem.DataBind();
                //lblTotal.Text = String.Format("{0:###,###}", ShoppingCart.GetTotalShoppingCart(ListShopCart).ToString());
                // item starkit
                if (Session["UserName"] != null)
                {
                    //kiểm tra xem có phải đơn hàng đầu tiên
                    if (ShoppingCart.CheckFirstOrderBySalespKey(ref error, Session["UserName"].ToString()))
                    {
                        List<ShoppingCart> ListItemStartKit = new List<ShoppingCart>();
                        ListItemStartKit = ShoppingCart.GetItemStartKit(ref error);
                        Session["ItemStartKit"] = ListItemStartKit;
                        GridViewItemStarkit.DataSource = ListItemStartKit;
                        GridViewItemStarkit.DataBind();
                        GridViewItemStarkit.Visible = true;
                    }
                    else
                    {
                        Session["ItemStartKit"] = null;
                        GridViewItemStarkit.Visible=false;
                    }
                }
            }
            //else
            //lblTotal.Text = "0";
        }
    }
}